﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using School.Entities;
using School.Common;

namespace School.Pages.Bus
{
    public partial class Bus_order : System.Web.UI.Page
    {
        private static SchoolEntities db = new SchoolEntities();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1201) == true)
                {
                    if (!this.Page.IsPostBack)
                        FillControls();
                    lbltst.Visible = false;
                    lblprice.Visible = false;
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
            if (!IsPostBack)
            {
                var q = School.Service.Bus.GetBusDistforddl(0).ToList();
                ddlDistrict.DataSource = q;
                ddlDistrictback.DataSource = q;
                ddlBind(ddlDistrict);
                ddlBind(ddlDistrictback);
            }
        }
        private void FillControls()
        {
            ddlCampus.DataSource = School.Uniform.PayOrder.AllCampus();
            ddlCampus.DataBind();
        }
        private void ddlBind(DropDownList ddl)
        {
            ddl.Items.Clear();
            ddl.Items.Insert(0, new ListItem("اختيار", "0"));
            ddl.DataBind();
        }
        protected void ddlCertificate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCertificate.SelectedValue != "0")
            {
                ddlStadge.DataSource = School.Uniform.PayOrder.GetStadgeByCertificate(int.Parse(ddlCertificate.SelectedValue));
                ddlBind(ddlStadge);
            }

        }
        protected void ddlStadge_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlStadge.SelectedValue != "0")
            {
                ddlGrade.DataSource = School.Uniform.PayOrder.GetGradeByStadge(int.Parse(ddlStadge.SelectedValue));
                ddlBind(ddlGrade);
            }

        }
        protected void ddlCampus_TextChanged(object sender, EventArgs e)
        {
            if (ddlCampus.SelectedValue != "0")
            {

                ddlCertificate.DataSource = School.Uniform.PayOrder.GetCertificateByCamp(int.Parse(ddlCampus.SelectedValue));
                ddlBind(ddlCertificate);
                //ddlBind(ddlbus, School.Service.Bus.GetBusByCamp(Convert.ToInt32(ddlCampus.SelectedValue.ToString())).ToList());
                ddlBind(ddlbusback, School.Service.Bus.GetBusByCamp(Convert.ToInt32(ddlCampus.SelectedValue.ToString())).ToList());
                //DropDownList1
                // ddlBind(DropDownList1, School.Service.Bus.GetBusByCamp(Convert.ToInt32(ddlCampus.SelectedValue.ToString())).ToList());
            }
        }
        protected void ddlGrade_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlGrade.SelectedValue != "0")
            {
                ddlstudent.DataSource = School.Service.Bus.AllFullName_Notinbus(Convert.ToInt32(ddlCampus.SelectedValue), Convert.ToInt32(ddlCertificate.SelectedValue), Convert.ToInt32(ddlStadge.SelectedValue), int.Parse(ddlGrade.SelectedValue));
                ddlBind(ddlstudent);
            }
        }
        private void ddlBind(DropDownList ddl, object o)
        {
            ddl.DataSource = o;
            ddl.Items.Clear();
            ddl.Items.Insert(0, new ListItem("اختيار", "0"));
            ddl.DataBind();
        }
        protected void ddlbus_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*if (ddlbus.SelectedValue != "0")
            {
                var q = School.Service.Bus.GetBusDistforddl(int.Parse(ddlbus.SelectedValue));
                ddlDistrict.DataSource = q.ToList();
                ddlBind(ddlDistrict);

            }*/
        }

        protected void ddlDistrict_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDistrict.SelectedValue != "0")
            {
                IEnumerable<SRV_Bus_Station> query = School.Service.Bus.GetstationdllBy(int.Parse(ddlDistrict.SelectedValue));
                //  var q = from a in query join b in db.SRV_Bus_Station_Price on a.Id equals b.Station_Id orderby a.Name select a;
                ddlstation.DataSource = query.ToList();
                ddlBind(ddlstation);
            }
        }
        public int pric_disc_id = 0;
        
        protected void btndiscount_Click(object sender, EventArgs e)
        {

            if (rdblSubscription.SelectedIndex == 0)
            {
                Page.Validate("go");
            }
            else if (rdblSubscription.SelectedIndex == 1)
            {
                Page.Validate("ba");
            }
            else if (rdblSubscription.SelectedIndex == 2)
            {
                Page.Validate("temp");
            }
            else
                Page.Validate("temp");

            if (Page.IsValid)
            {
                disbind();
                gvdiscountBind();
                pldiscount.Visible = true;


            }
        }

        private void disbind()
        {
            if (rdblSubscription.SelectedIndex >= 0)
            {
                decimal Price_Discount = 0;
                int id = 2;
                if (rdblSubscription.SelectedValue == "0")
                    id = 1;
                else if (rdblSubscription.SelectedValue == "1")
                    id = 1;
                else if (rdblSubscription.SelectedValue == "2")
                    id = 2;
                else if (rdblSubscription.SelectedValue == "3" || rdblSubscription.SelectedValue == "4")
                    id = 3;
                else
                    id = 0;
                if (id == 1 || id == 2 || id == 3)
                {
                    var q = School.Service.Bus.GetPrice_DiscountByid(id);
                    Price_Discount = Convert.ToDecimal(q.FirstOrDefault().Discount);
                    HFdis.Value = Price_Discount.ToString();
                }
                else
                    HFdis.Value = "0";
                HfDicId.Value = id.ToString();
            }
        }
        private void gvdiscountBind()
        {
            int fjd = 0, mjd = 0, fsd = 0, msd = 0;
            var fjid = School.Service.Bus.getfatherjob(Convert.ToInt32(ddlstudent.SelectedValue));
            if (fjid.Count() != 0)
                fjd = fjid.First().Id;
            var mjid = School.Service.Bus.getmotherjob(Convert.ToInt32(ddlstudent.SelectedValue));
            if (mjid.Count() != 0)
                mjd = mjid.First().Id;
            var fsid = School.Service.Bus.getfatherStatus(Convert.ToInt32(ddlstudent.SelectedValue));
            if (fsid.Count() != 0)
                fsd = fsid.First().Id;
            var msid = School.Service.Bus.getmotherStatus(Convert.ToInt32(ddlstudent.SelectedValue));
            if (msid.Count() != 0)
                msd = msid.First().Id;

            gvdiscount.DataSource = School.Common.Finance.GetDiscounts("200", Convert.ToInt32(ddlCampus.SelectedValue), Convert.ToInt32(ddlCertificate.SelectedValue), Convert.ToInt32(ddlStadge.SelectedValue), Convert.ToInt32(ddlGrade.SelectedValue), fjd, fsd, mjd, msd);
            gvdiscount.DataBind();
        }
        protected void ddlbusback_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*if (ddlbusback.SelectedValue != "0")
            {
                var q = School.Service.Bus.GetBusDistforddl(int.Parse(ddlbusback.SelectedValue));
                ddlDistrictback.DataSource = q.ToList();
                ddlBind(ddlDistrictback);
            }*/
        }
        protected void ddlDistrictback_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDistrictback.SelectedValue != "0")
            {
                IEnumerable<SRV_Bus_Station> query = School.Service.Bus.GetstationdllBy(int.Parse(ddlDistrictback.SelectedValue));
                ddlstationback.DataSource = query.ToList();
                ddlBind(ddlstationback);
            }
        }
        protected void btnpayment_Click(object sender, EventArgs e)
        {
            bool bu = false;
            int Passenger_number = 0;
            int paback = 0;
            if (PLGo.Visible == true && Plback.Visible == true)
            {
                Passenger_number = School.Service.Bus.GetPassenger_numberById(Convert.ToInt32(ddlbus.SelectedValue));
                paback = School.Service.Bus.GetPassenger_numberById(Convert.ToInt32(ddlbusback.SelectedValue));
                if (Passenger_number != 0 && Passenger_number != null && paback != 0 && Passenger_number != null)
                {
                    bu = true;

                }
                else
                    bu = false;
            }
            else if (PLGo.Visible == true)
            {
                Passenger_number = School.Service.Bus.GetPassenger_numberById(Convert.ToInt32(ddlbus.SelectedValue));

                if (Passenger_number != 0 && Passenger_number != null)
                {
                    bu = true;
                }
                else
                    bu = false;
            }
            else
            {
                paback = School.Service.Bus.GetPassenger_numberById(Convert.ToInt32(ddlbusback.SelectedValue));
                if (paback != 0 && Passenger_number != null)
                { bu = true; }
                else
                    bu = false;
            }
            if (bu)
            {
                bool re = true;
                long Pay_order = School.Common.Structure.GetPayment_Order_Number();
                long EDy_id = School.Service.Bus.Education_Yearid();
                int? x;
                if (HfDicId.Value == " 0" || HfDicId.Value == null || HfDicId.Value == "")
                {
                    x = null;
                }
                else
                    x = Convert.ToInt32(HfDicId.Value.ToString());
                if (lblprice.Visible == false)
                    priceBind();
                long id = 0;
                if (PLGo.Visible == true && Plback.Visible == true)
                    id = School.Service.Bus.AddPayment_Order(int.Parse(ddlstudent.SelectedValue), Pay_order, int.Parse(ddlbus.SelectedValue), int.Parse(ddlstation.SelectedValue), int.Parse(ddlbusback.SelectedValue), int.Parse(ddlstationback.SelectedValue), x, Convert.ToDecimal(lblprice.Text), EDy_id);
                else if (PLGo.Visible == true)
                    id = School.Service.Bus.AddPayment_Order(int.Parse(ddlstudent.SelectedValue), Pay_order, int.Parse(ddlbus.SelectedValue), int.Parse(ddlstation.SelectedValue), null, null, x, Convert.ToDecimal(lblprice.Text), EDy_id);
                else
                    id = School.Service.Bus.AddPayment_Order(int.Parse(ddlstudent.SelectedValue), Pay_order, null, null, int.Parse(ddlbusback.SelectedValue), int.Parse(ddlstationback.SelectedValue), x, Convert.ToDecimal(lblprice.Text), EDy_id);
                if (gvdiscount.Rows.Count > 0)
                    foreach (GridViewRow Row in gvdiscount.Rows)
                    {
                        CheckBox chdis = (CheckBox)Row.FindControl("chdis");
                        if (chdis.Checked)
                        {
                            int key = Convert.ToInt32(gvdiscount.DataKeys[Row.RowIndex].Value.ToString());
                            byte type = Convert.ToByte(gvdiscount.DataKeys[Row.RowIndex].Values["Type"].ToString());
                            decimal Value = Convert.ToDecimal(gvdiscount.DataKeys[Row.RowIndex].Values["Value"].ToString());
                            re = School.Service.Bus.AddPayment_ORDER_Discount(id, key, type, Value);
                        }
                    }

                if (re)
                {

                    HfId.Value = id.ToString();
                    SchoolEntities db = new SchoolEntities();
                    paymentOrderGrid.DataSource = from xp in db.SRV_Bus_Payment_Order where xp.Id == id select new { Number = xp.Payment_order_num, Value = xp.Value };
                    paymentOrderGrid.DataBind();
                    paymentOrderPanel.Visible = true;                    
                }
                else
                    lbltst.Text = "Failed";
                lbltst.Visible = true;
            }
            else
            {
                lbltst.Text = "لايوجد أماكن فارغة في هذا الباص";
                lbltst.Visible = true;
                pldiscount.Visible = false;
            }
        }
        protected string GetType(object type)
        {
            return type.ToString() == "1" ? "مبلغ" : "نسبة";
        }
        protected string GetValue(object type, object value)
        {
            if (type.ToString() == "1")
                return value.ToString() + " جنيه";
            else
                return value.ToString() + "%";
        }

        protected void btntotal_Click(object sender, EventArgs e)
        {
            priceBind();
        }

        private void priceBind()
        {
            var ORDER_Discount = School.Service.Bus.ORDER_Discounts(Convert.ToInt32(ddlCampus.SelectedValue), Convert.ToInt32(ddlCertificate.SelectedValue), Convert.ToInt32(ddlStadge.SelectedValue));
            decimal Increase_Value = 0;
            double Increase_percent = 0;
            decimal Grade_Increase_Value = 0;
            double Grade_Increase_Percent = 0;

            if (ORDER_Discount.Count() > 0)
            {
                Increase_Value = ORDER_Discount.FirstOrDefault().Increase_Value;
                Increase_percent = ORDER_Discount.FirstOrDefault().Increase_percent;
                Grade_Increase_Value = ORDER_Discount.FirstOrDefault().Grade_Increase_Value;
                Grade_Increase_Percent = ORDER_Discount.FirstOrDefault().Increase_percent;
            }
            decimal bus_price = 0;
            decimal dis = 0;
            disbind();
            lblprice.Visible = true;
            if (PLGo.Visible == true && Plback.Visible == true)
            {
                var query = School.Service.Bus.GetStation_Price(Convert.ToInt32(ddlbus.SelectedValue), Convert.ToInt32(ddlDistrict.SelectedValue), Convert.ToInt32(ddlstation.SelectedValue));
                if (query.Count() != 0)
                    bus_price = Convert.ToDecimal(query.First().Price);
                var queryBack = School.Service.Bus.GetStation_Price(Convert.ToInt32(ddlbusback.SelectedValue), Convert.ToInt32(ddlDistrictback.SelectedValue), Convert.ToInt32(ddlstationback.SelectedValue));
                if (queryBack.Count() != 0)
                    if (Convert.ToDecimal(queryBack.First().Price) > Convert.ToDecimal(query.First().Price))
                        bus_price = Convert.ToDecimal(queryBack.First().Price);
            }
            else if (PLGo.Visible == true)
            {
                var query = School.Service.Bus.GetStation_Price(Convert.ToInt32(ddlbus.SelectedValue), Convert.ToInt32(ddlDistrict.SelectedValue), Convert.ToInt32(ddlstation.SelectedValue));
                if (query.Count() != 0)
                    bus_price = Convert.ToDecimal(query.First().Price);

            }
            else
            {
                var queryBack = School.Service.Bus.GetStation_Price(Convert.ToInt32(ddlbusback.SelectedValue), Convert.ToInt32(ddlDistrictback.SelectedValue), Convert.ToInt32(ddlstationback.SelectedValue));
                if (queryBack.Count() != 0)
                    bus_price = Convert.ToDecimal(queryBack.First().Price);

            }
            if (gvdiscount.Rows.Count > 0)
            {
                foreach (GridViewRow Row in gvdiscount.Rows)
                {
                    CheckBox chdis = (CheckBox)Row.FindControl("chdis");
                    if (chdis.Checked)
                    {
                        byte Type = Convert.ToByte(gvdiscount.DataKeys[Row.RowIndex].Values["Type"].ToString());

                        decimal Value = Convert.ToDecimal(gvdiscount.DataKeys[Row.RowIndex].Values["Value"].ToString());

                        if (Type == 1)
                        {
                            dis += Value;
                        }
                        else
                        {
                            dis += ((bus_price * Value) / 100);
                        }
                    }
                }
            }
            if (Increase_Value != 0)
            {
                decimal dc = Convert.ToDecimal(Increase_Value);
                bus_price = (dc + bus_price);

            }
            else if (Increase_percent != 0)
            {
                decimal d = Convert.ToDecimal(Increase_percent);
                bus_price = (((d * bus_price) / 100) + bus_price);

            }
            else if (Grade_Increase_Value != 0)
            {
                decimal dc = Convert.ToDecimal(Grade_Increase_Value);
                bus_price = (dc + bus_price);



            }
            else if (Grade_Increase_Percent != 0)
            {
                decimal d = Convert.ToDecimal(Grade_Increase_Percent);
                bus_price = (((d * bus_price) / 100) + bus_price);
            }
            decimal di = Convert.ToDecimal(HFdis.Value.ToString());
            if (di != 0 && di != null)
                bus_price = bus_price - ((di * bus_price) / 100);

            lblprice.Text = (bus_price - (dis)).ToString();
        }
        protected void rdblSubscription_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rdblSubscription.SelectedIndex == 0)
            {
                PLGo.Visible = true;
                Plback.Visible = false;
                PlBus.Visible = true;
            }
            else if (rdblSubscription.SelectedIndex == 1)
            {

                PLGo.Visible = false;
                Plback.Visible = true;
                PlBus.Visible = true;
            }
            else if (rdblSubscription.SelectedIndex == 2)
            {
                PLGo.Visible = true;
                Plback.Visible = true;
                PlBus.Visible = true;
            }
            else if (rdblSubscription.SelectedIndex == 3)
            {
                PLGo.Visible = true;
                Plback.Visible = false;
                PlBus.Visible = true;
            }
            else if (rdblSubscription.SelectedIndex == 4)
            {
                PLGo.Visible = false;
                Plback.Visible = true;
                PlBus.Visible = true;
            }
            else
            {
                PLGo.Visible = true;
                Plback.Visible = true;
                PlBus.Visible = true;

            }


        }

        protected void ddlCampus_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void OdsDiscount_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {

            e.InputParameters["payment_id"] = int.Parse(HfId.Value.ToString());
        }

        protected void OdsOrder_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["payment_id"] = int.Parse(HfId.Value.ToString());
        }

        protected void ddlstudent_SelectedIndexChanged(object sender, EventArgs e)
        {
            HFStudent.Value = ddlstudent.SelectedValue;
        }

        protected void ddlstation_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlBind(ddlbus, School.Service.Bus.GetBusByStation(Convert.ToInt32(ddlstation.SelectedValue)).ToList());
            ddlBind(ddlbus);
        }

        protected void ddlstationback_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlBind(ddlbusback, School.Service.Bus.GetBusByStation(Convert.ToInt32(ddlstationback.SelectedValue)).ToList());
            ddlBind(ddlbusback);
        }

        protected void StudentsGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            HFStudent.Value = ((Label)StudentsGrid.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("LblStudentId")).Text;
            StudentsPanel.Visible = false;
            var id = long.Parse(HFStudent.Value);
            var student = db.TE_Student.Single(x => x.Id == id);
            
            ddlCampus.SelectedValue = student.Campus_Id.ToString();
            ddlCampus_TextChanged(ddlCampus, null);

            ddlCertificate.SelectedValue = student.Certificate_Id.ToString();
            ddlCertificate_SelectedIndexChanged(ddlCertificate, null);

            ddlStadge.SelectedValue = student.Stage_Id.ToString();
            ddlStadge_SelectedIndexChanged(ddlStadge, null);

            ddlGrade.SelectedValue = student.Grade_ID.ToString();
            ddlGrade_SelectedIndexChanged(ddlGrade, null);

            ddlstudent.SelectedValue = student.Id.ToString();
            //ddlstudent_SelectedIndexChanged(null, null);
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            long id = 0;
            string name = null;

            long.TryParse(TxtStudentNumber.Text, out id);
            name = TxtStudentName.Text;

            var d = Students.Search(id, name);

            if (d.Count() > 0)
            {
                StudentsGrid.DataSource = d;
                StudentsGrid.DataBind();
                StudentsPanel.Visible = true;
                StudentsGrid.Visible = true;
                LblSearchNotFound.Visible = false;
            }
            else
            {
                StudentsPanel.Visible = true;
                LblSearchNotFound.Visible = true;
                StudentsGrid.Visible = false;
            }

            TxtStudentName.Text = "";
            TxtStudentNumber.Text = "";                       
        }
    }
}
